package com.tianji.StragyHttp.utils;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tianji.StragyHttp.constant.ThreadPoolConstant;
import com.tianji.StragyHttp.dto.CrmHttpReqDTO;
import com.tianji.StragyHttp.dto.CrmHttpRespDTO;
import com.tianji.StragyHttp.enumr.PlatformEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static com.tianji.StragyHttp.constant.ThreadPoolConstant.HTTP_SUB_API_THREAD_BEAN;


/**
 * 直接调用子系统方法工具类
 */
@Slf4j
@Component
public class CrmHttpApiUtil {


    private static String TB_URL;
    private static String JD_URL;
    private static String DY_URL;
    private static String KS_URL;
    private static String YZ_URL;

    public static String getTbUrl() {
        return TB_URL;
    }

    @Value("${tb.web.api.url}")
    public void setTbUrl(String tbUrl) {
        TB_URL = tbUrl;
    }

    public static String getJdUrl() {
        return JD_URL;
    }

    @Value("${jd.web.api.url}")
    public void setJdUrl(String jdUrl) {
        JD_URL = jdUrl;
    }

    public static String getDyUrl() {
        return DY_URL;
    }

    @Value("${dy.web.api.url}")
    public void setDyUrl(String dyUrl) {
        DY_URL = dyUrl;
    }

    public static String getKsUrl() {
        return KS_URL;
    }

    @Value("${ks.web.api.url}")
    public void setKsUrl(String ksUrl) {
        KS_URL = ksUrl;
    }

    public static String getYzUrl() {
        return YZ_URL;
    }

    @Value("${yz.web.api.url}")
    public void setYzUrl(String yzUrl) {
        YZ_URL = yzUrl;
    }


    /**
     * 异步编排执行所有sub http请求
     *
     * @param reqDTOs 请求入参列表
     * @return 结果集
     */
    public static List<CrmHttpRespDTO> httpSubApis(List<CrmHttpReqDTO> reqDTOs) {
        if (CollUtil.isEmpty(reqDTOs)) {
            return Collections.emptyList();
        }
        // 异步编排
        ExecutorService executorService = SpringContextHolder.getBean(HTTP_SUB_API_THREAD_BEAN);
        List<CompletableFuture<CrmHttpRespDTO>> futures = new ArrayList<>(reqDTOs.size());
        reqDTOs.forEach(reqDTO ->
                futures.add(CompletableFuture.supplyAsync(() -> httpSubApi(reqDTO), executorService)));
        // 等待所有http请求完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        return futures.stream().map(CompletableFuture::join).collect(Collectors.toList());
    }

    /**
     * 请求子系统接口通用方法
     *
     * @param reqDTO 请求dto
     * @return 结果json
     */
    public static CrmHttpRespDTO httpSubApi(CrmHttpReqDTO reqDTO) {
        CrmHttpRespDTO respDTO = new CrmHttpRespDTO();
        if (StrUtil.isBlank(reqDTO.getRequestId())) {
            reqDTO.setRequestId(UUID.randomUUID().toString());
        }
        respDTO.setRequestId(reqDTO.getRequestId());
        respDTO.setPlatformCode(reqDTO.getPlatformEnum().getCode());
        try {
            String url = getSubApiUrl(reqDTO.getPath(), reqDTO.getPlatformEnum());
            String result;

            if (Method.GET == reqDTO.getMethod()) {
                HttpRequest httpRequest = HttpUtil.createGet(url)
                        .header("token", reqDTO.getJwt())
                        .form(reqDTO.getParamMap())
                        .timeout(300000);
                result = httpRequest.execute().body();
            } else {
                HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
                factory.setConnectTimeout(300000);
                RestTemplate restTemplate = new RestTemplate(factory);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                headers.set("token", reqDTO.getJwt());
                HttpEntity<JSONObject> entity = new HttpEntity<>(reqDTO.getBody(), headers);
                ResponseEntity<String> r = restTemplate.postForEntity(url, entity, String.class);
                result = r.getBody();
            }
            JSONObject jsonObject = JSONUtil.parseObj(result);
            int code = jsonObject.getInt("code", 0);

            if (code == 200 || code == 1) {
                respDTO.setData(jsonObject.get("data"));
                return respDTO;
            } else {
                log.warn("子系统接口报错,平台:{},返回：{}", reqDTO.getPlatformEnum().getName(), result);
                return respDTO;
            }
        } catch (Exception e) {
            log.error("子系统接口调用异常,平台:{}", reqDTO.getPlatformEnum().getName(), e);
            return respDTO;
        }
    }


    /**
     * 拼接接口地址
     *
     * @param path
     * @param platformEnum
     * @return
     */
    private static String getSubApiUrl(String path, PlatformEnum platformEnum) {

        String url = "";

        String code = platformEnum.getCode();

        switch (code) {
            case "TB":
                url = TB_URL + path;
                break;
            case "JD":
                url = JD_URL + path;
                break;
            case "DY":
                url = DY_URL + path;
                break;
            case "YZ":
                url = YZ_URL + path;
                break;
            case "KS":
                url = KS_URL + path;
                break;
            default:
                break;
        }

        return url;
    }



}
